package com.yanghx.transaction.service;

import com.yanghx.transaction.dao.CustomerRepostory;
import com.yanghx.transaction.entity.Customer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;

/**
 * 代码事务
 *
 * @author yangHX
 * createTime  2019/8/9 0:27
 */
@Service
@Slf4j
public class CustomerServiceInCode {

    @Resource
    private CustomerRepostory customerRepostory;

    @Resource
    private PlatformTransactionManager transactionManager;
    @Resource
    private JmsTemplate jmsTemplate;


    public Customer create(Customer customer) {
        log.info("CustomerService IN CODE create customer :{}", customer.getUsername());
        if (customer.getId() != null) {
            throw new RuntimeException("用户已存在");
        }
        DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
//        definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        definition.setTimeout(15);
        TransactionStatus transaction = transactionManager.getTransaction(definition);
        try {
            customer.setUsername("Code:" + customer.getUsername());
            customerRepostory.save(customer);
            jmsTemplate.convertAndSend("customer:msg:reply", customer.getUsername() + "created.");
            transactionManager.commit(transaction);
            return customer;
        } catch (Exception e) {
            transactionManager.rollback(transaction);
            throw e;
        }
    }

    @JmsListener(destination = "customer:msg2:new")
    public void createByListener(String name) {
        log.info("CustomerService In Code by Listener create customer:{}", name);
        Customer customer = new Customer();
        customer.setUsername("Code:" + name);
        customer.setRole("USER");
        customer.setPassword("111111");

        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        def.setTimeout(15);
        TransactionStatus transaction = transactionManager.getTransaction(def);

        try {
            customerRepostory.save(customer);
            jmsTemplate.convertAndSend("customer:msg:reply", customer.getUsername() + "created.");
            transactionManager.commit(transaction);
        } catch (Exception e) {
            transactionManager.rollback(transaction);
            throw e;
        }
    }

}
